package Thread;

import java.util.Scanner;

/**
 * @projectName: Thread-20250806
 * @package: Thread
 * @className: Homework5
 * @author: Tongxinxin
 * @description: 手写一个死锁代码
 * 提示：可以通过 synchronized 或者 Lock 来实现一个死锁代码。
 * 所谓的死锁就是线程一拥有锁1，线程二拥有锁2，双方在拥有自身锁的同时尝试获取对方的锁，最终两个线程就会进入无线等待的状态，这就是死锁。
 * @date: 2025/8/9 21:03
 * @version: 1.0
 */
public class Homework5 {
//    private static int flag=0;
// 创建两个对象作为锁
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();
    public static void main(String[] args) throws InterruptedException {
//        Thread t1=new Thread(()->{
//            while(flag==0){
//
//            }
//            System.out.println("t1线程结束");
//        });
//        Thread t2=new Thread(()->{
//            Scanner scanner=new Scanner(System.in);
//            System.out.println("输入flag的值：");
//            flag=scanner.nextInt();
//        });
//        t1.start();
//        t2.start();
//    }
// 线程1：先获取lock1，再尝试获取lock2
    Thread thread1 = new Thread(() -> {
        synchronized (lock1) {
            System.out.println("线程1获取lock1");
            try {
                Thread.sleep(100); // 睡眠确保线程2能获取到lock2
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock2) {
                System.out.println("线程1获取lock2");
            }
        }
    });

    // 线程2：先获取lock2，再尝试获取lock1
        Thread thread2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println("线程2获取lock2");
                try {
                    Thread.sleep(100); // 睡眠确保线程1能获取到lock1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("线程2获取lock1");
                }
            }
        });
        // 启动两个线程
        thread1.start();
        thread2.start();
        System.out.println("主线程结束，但程序会因为死锁而无法退出");
    }
}
